let pollingTimer = null;
let lastSrcs = [];
const scriptReg = /<script.*src=["'](?<src>[^"']+)/gm;

/**
 * 获取首页 HTML 并提取 script src 列表
 */
const fetchHtml = async () => {
	try {
		const res = await fetch('/?_timestamp=' + Date.now(), {
			cache: 'no-cache',
		});
		const html = await res.text();
		scriptReg.lastIndex = 0;
		const srcs = [];
		let match;
		while ((match = scriptReg.exec(html))) {
			srcs.push(match.groups.src);
		}
		return srcs;
	} catch (e) {
		// 网络异常时返回上次的srcs，避免worker崩溃
		return lastSrcs || [];
	}
};

/**
 * 比较 script src 列表是否有变化
 */
const compareSrcAndEtag = (srcs) => {
	if (!lastSrcs.length) {
		lastSrcs = srcs;
		return false;
	}
	if (srcs.length !== lastSrcs.length) {
		lastSrcs = srcs;
		return true;
	}
	for (let i = 0; i < srcs.length; i++) {
		if (srcs[i] !== lastSrcs[i]) {
			lastSrcs = srcs;
			return true;
		}
	}
	return false;
};

/**
 * 停止轮询
 */
const stopPolling = () => {
	if (pollingTimer) clearTimeout(pollingTimer);
	pollingTimer = null;
};

/**
 * 启动轮询检测
 */
const startPolling = (interval = 5000) => {
	stopPolling();
	const checkUpdate = async () => {
		const srcs = await fetchHtml();
		if (compareSrcAndEtag(srcs)) {
			self.postMessage({ type: 'UPDATE' });
		}
		pollingTimer = setTimeout(checkUpdate, interval);
	};
	checkUpdate();
};

// 监听主线程消息
self.onmessage = (e) => {
	if (e.data.type === 'INIT') {
		const { pollingInterval } = e.data.payload;
		startPolling(Number(pollingInterval) || 5000);
	}
	if (e.data.type === 'TERMINATE') {
		stopPolling();
		self.close();
	}
};
